package com.onenine.app.fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.onenine.app.R;
import com.onenine.app.listener.OnLoginListener;
import com.onenine.app.request.GetBoundCodeRequest;
import com.onenine.app.request.GetCodeRequest;
import com.onenine.app.response.GetCodeResponse;
import com.onenine.app.utils.CHelper;
import com.onenine.app.utils.UrlConfig;
import com.onenine.app.view.LoadingButton;
import com.onenine.app.view.uppanel.SlidingUpPanelLayout;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.base.utils.Toasty;
import com.onenine.common.util.FragmentUtils;
import com.onenine.common.util.KeyboardUtils;
import com.onenine.common.util.RegexUtils;

/**
 * 手机登录或绑定
 */
public class LoginMobileFragment extends Fragment implements TextWatcher, View.OnClickListener {

    private EditText mEditPhone;
    private String mOpenId, mUserId;
    private TextView mTvTile;
    private LoadingButton mBtnLoading;
    private OnLoginListener mOnLoginListener;

    public static Fragment newInstance() {
        return new LoginMobileFragment();
    }

    public static Fragment newInstance(String userId, String openId) {
        Fragment fragment = new LoginMobileFragment();
        Bundle args = new Bundle();
        args.putString("userId", userId);
        args.putString("openId", openId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mOpenId = getArguments().getString("openId");
        mUserId = getArguments().getString("userId");
        mTvTile.setText(mOpenId != null ? R.string.phone_bind : R.string.phone_login_register);
        mOnLoginListener = (OnLoginListener) getActivity();
        SlidingUpPanelLayout upPanelLayout = mOnLoginListener.getUpPanelLayout();
        upPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
        KeyboardUtils.showSoftInput(mEditPhone);
        mEditPhone.requestFocus();
        mEditPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                upPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
            }
        });
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_login_mobile, container, false);
        mTvTile = view.findViewById(R.id.tv_mobile_title);
        mEditPhone = view.findViewById(R.id.edt_mobile);
        mEditPhone.addTextChangedListener(this);
        mBtnLoading = view.findViewById(R.id.btn_loading);
        mBtnLoading.setButtonEnable(false);
        mBtnLoading.setButtonText(R.string.get_phone_code);
        mBtnLoading.setButtonOnClickListener(this);
        return view;
    }

    /**
     * 获取手机验证码
     *
     * @param phoneNum
     */
    private void getSmsCode(final String phoneNum) {
        mBtnLoading.setLoading(true);
        OkRequest.getInstance().withRequest(new GetCodeRequest(phoneNum))
                .withUrl(UrlConfig.SEND_CODE).doRequest(getClass().getSimpleName(), new OkCallback<GetCodeResponse>() {
            @Override
            public void onResponse(GetCodeResponse response, String srcData) {
                if (response.isSuccess()) {
                    //FIXME 吐司上线后要删除
                    if (!CHelper.isReleaseEnv()) {
                        Toasty.showNormal("验证码：" + response.getSendCode());
                    }
                    FragmentUtils.replace(getFragmentManager()
                            , LoginSmsFragment.newInstance(phoneNum), R.id.fl_content, true);
                } else {
                    Toasty.showNormal(response.getMessage());
                }
                mBtnLoading.setLoading(false);
            }
        });
    }

    /**
     * 获取绑定手机的短信验证码
     *
     * @param phoneNum
     */
    private void getBoundSmsCode(final String phoneNum, final String openId) {
        mBtnLoading.setLoading(true);
        OkRequest.getInstance().withRequest(new GetBoundCodeRequest(phoneNum, openId))
                .withUrl(UrlConfig.BIND_SEND_CODE).doRequest(getClass().getSimpleName(), new OkCallback<GetCodeResponse>() {
            @Override
            public void onResponse(GetCodeResponse response, String srcData) {
                if (response.isSuccess()) {
                    //FIXME 吐司上线后要删除
                    if (!CHelper.isReleaseEnv()) {
                        Toasty.showNormal("验证码：" + response.getSendCode());
                    }
                    FragmentUtils.replace(getFragmentManager()
                            , LoginSmsFragment.newInstance(phoneNum, mUserId, openId), R.id.fl_content, true);
                } else {
                    Toasty.showNormal(response.getMessage());
                }
                mBtnLoading.setLoading(false);
            }
        });
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        mBtnLoading.setButtonEnable(s.length() == 11);
    }

    @Override
    public void onClick(View v) {
        final String phoneNum = mEditPhone.getText().toString().trim();
        if (!RegexUtils.isMobileExact(phoneNum)) {
            Toasty.showNormal(R.string.phone_num_invalid);
            mEditPhone.requestFocus();
            mBtnLoading.setButtonEnable(false);
        } else {
            if (mOpenId == null) {
                getSmsCode(phoneNum);
            } else {
                getBoundSmsCode(phoneNum, mOpenId);
            }
        }
    }

}
